//
//  AlertButton.m
//  IntelligenceCommunity
//
//  Created by zhangpei on 15/12/23.
//  Copyright © 2015年 zhangpei. All rights reserved.
//

#import "AlertButton.h"
#import "UtilityConfig.h"

@interface AlertButton ()
{
    UIWindow *window;
}

@property (nonatomic, strong) UIButton *button;

@end

static AlertButton *alertButton;

@implementation AlertButton

@synthesize alertButtonBlock;

@synthesize button;


+ (id)sharedAlertButtonWithTitle:(NSString *)title withAlertButtonBlock:(AlertButtonBlock)block
{
    @synchronized (self)
    {
        //为了确保多线程情况下，仍然确保实体的唯一性
        if (alertButton == nil)
        {
            alertButton = [[AlertButton alloc] init];
        }
        
        alertButton.alertButtonBlock = [block copy];

        [alertButton.button setTitle:title forState:UIControlStateNormal];
        
        alertButton.hidden = NO;
        
        //window 弹出alert
        [WINDOW addSubview:alertButton];
        
        return alertButton;
    }
}


+ (id)allocWithZone:(NSZone *)zone
{
    @synchronized(self)
    {
        if (!alertButton)
        {
            alertButton = [super allocWithZone:zone]; //确保使用同一块内存地址
            
            return alertButton;
        }
        
        return nil;
    }
}


- (instancetype)init
{
    self = [super init];
    
    if (self)
    {
        self.hidden = YES;
        [self initView];
    }
    return self;
}



- (void)initView
{
       
    window = [[[UIApplication sharedApplication] windows] objectAtIndex:0];
    self.frame = window.bounds;
    [window addSubview:self];
    
    //灰色覆层
    UIImageView *grayImageView = [[UIImageView alloc] initWithFrame:self.bounds];
    grayImageView.backgroundColor = [UIColor colorWithRed:121.f/255.f green:121.f/255.f blue:121.f/255.f alpha:0.7f];
    [self addSubview:grayImageView];
    
    button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.backgroundColor = [UIColor whiteColor];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    button.frame = CGRectMake(30, 0, self.bounds.size.width - 60, 35);
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    button.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [button addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
    button.center = self.center;
    [self addSubview:button];
}

- (void)buttonClick
{
    if (alertButtonBlock)
    {
        self.hidden = YES;
        alertButtonBlock(button.currentTitle);
    }
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    self.hidden = YES;
}


@end
